<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\CarOwner;
use App\Models\ScanLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;

class ScanController extends Controller
{
    /**
     * 解析二维码数据
     */
    public function decodeQrCode(Request $request)
    {
        $request->validate([
            'qr_data' => 'required|string'
        ]);
        
        $qrData = $request->input('qr_data');
        
        try {
            // 首先检查是否为微信小程序码的scene值
            if (strlen($qrData) <= 32) {
                $origData = Cache::get("qrcode_scene:{$qrData}");
                if (!$origData) {
                    throw new \Exception('找不到对应的二维码数据');
                }
                
                // 将原始数据替换为scene对应的数据
                $qrData = $origData;
            }
            
            // 解密二维码数据
            $decodedData = decrypt($qrData);
            $carOwnerId = $decodedData['id'];
            
            $carOwner = CarOwner::with('user:id,nickname,avatar_url')->findOrFail($carOwnerId);
            
            // 记录扫码日志
            $this->logScan(auth()->id(), $carOwnerId);
            
            return response()->json([
                'status' => 'success',
                'car_owner' => [
                    'id' => $carOwner->id,
                    'name' => $carOwner->user->nickname ?: '车主',
                    'avatar' => $carOwner->user->avatar_url,
                    'phone_number' => $carOwner->phone_number
                ]
            ]);
        } catch (\Exception $e) {
            Log::error('解析二维码失败', ['error' => $e->getMessage(), 'qr_data' => $qrData]);
            return response()->json([
                'status' => 'error',
                'message' => '无效的二维码'
            ], 400);
        }
    }
    
    /**
     * 记录拨打电话
     */
    public function logCallMade(Request $request)
    {
        $request->validate([
            'car_owner_id' => 'required|exists:car_owners,id'
        ]);
        
        try {
            // 查找最近的扫码记录并更新
            $scanLog = ScanLog::where('scanner_user_id', auth()->id())
                ->where('car_owner_id', $request->car_owner_id)
                ->orderBy('scan_time', 'desc')
                ->first();
                
            if ($scanLog) {
                $scanLog->call_made = true;
                $scanLog->save();
            } else {
                // 如果没有找到扫码记录，创建一个新的
                ScanLog::create([
                    'scanner_user_id' => auth()->id(),
                    'car_owner_id' => $request->car_owner_id,
                    'call_made' => true,
                    'ip_address' => request()->ip(),
                    'device_info' => substr(request()->userAgent(), 0, 255)
                ]);
            }
            
            return response()->json([
                'status' => 'success',
                'message' => '已记录拨打电话'
            ]);
        } catch (\Exception $e) {
            Log::error('记录拨打电话失败', ['error' => $e->getMessage()]);
            return response()->json([
                'status' => 'error',
                'message' => '记录失败'
            ], 500);
        }
    }
    
    /**
     * 记录扫码日志
     * 
     * @param int $scannerUserId
     * @param int $carOwnerId
     */
    protected function logScan($scannerUserId, $carOwnerId)
    {
        ScanLog::create([
            'scanner_user_id' => $scannerUserId,
            'car_owner_id' => $carOwnerId,
            'ip_address' => request()->ip(),
            'device_info' => substr(request()->userAgent(), 0, 255)
        ]);
    }
}
